from PyQt5.QtWidgets import QPushButton, QStyleOptionButton, QStyle
from PyQt5.QtCore import Qt, QPropertyAnimation, pyqtSignal, pyqtProperty,QEasingCurve
from PyQt5.QtGui import QPainter, QPaintEvent

class RotatableButton(QPushButton):
    rotationChanged = pyqtSignal(int)  # 旋转角度变化信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self._rotation = 0  # 当前旋转角度
        self.setCursor(Qt.PointingHandCursor)  # 设置小手光标

    @pyqtProperty(int)
    def rotation(self):
        return self._rotation

    @rotation.setter
    def rotation(self, angle):
        if self._rotation != angle:
            self._rotation = angle
            self.update()  # 触发重绘
            self.rotationChanged.emit(angle)

    def setRotation(self, angle):
        self.rotation = angle

    def startRotation(self, durationMs, startAngle, endAngle):
        # print(durationMs, " ", startAngle, " ", endAngle)
        self.anim = QPropertyAnimation(self, b"rotation")
        self.anim.setDuration(durationMs)
        self.anim.setStartValue(startAngle)
        self.anim.setEndValue(endAngle)
        self.anim.setEasingCurve(QEasingCurve.Linear)
        self.anim.start(QPropertyAnimation.DeleteWhenStopped)

    def paintEvent(self, event: QPaintEvent):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)  # 抗锯齿

        # 保存当前坐标系
        painter.save()

        # 设置旋转中心并旋转
        center = self.rect().center()
        painter.translate(center)
        painter.rotate(self._rotation)
        painter.translate(-center)

        # 绘制按钮内容（支持图标和文本）
        opt = QStyleOptionButton()
        self.initStyleOption(opt)
        self.style().drawControl(QStyle.CE_PushButton, opt, painter, self)

        # 恢复坐标系
        painter.restore()